//
//  ExchangeViewController.swift
//  worldexchange
//
//  Created by xionghao on 2019/1/8.
//  Copyright © 2019 xionghao. All rights reserved.
//

import UIKit
import MJRefresh


class ExchangeViewController: QMUICommonViewController {

    @IBOutlet weak var shopWrapperView: UIView!
    @IBOutlet weak var timeLabel: UILabel!
    @IBOutlet weak var denomiationLabel: UILabel!
    @IBOutlet weak var sellingLabel: UILabel!
    @IBOutlet weak var buyingLabel: UILabel!
    @IBOutlet weak var currencyLabel: UILabel!
    @IBOutlet weak var tableHeader: UIView!
    @IBOutlet weak var tableView: QMUITableView!
    @IBOutlet weak var currentShopNameLabel: UILabel!
    

    var openSection = -1
    
    
    @IBOutlet weak var refreshButton: UIButton!
    
    @IBOutlet weak var exchangeLabel: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        setupHeaderView()
        setupTableView()
        NotificationCenter.default.addObserver(self, selector: #selector(receiveMoneyLoadEnd), name: NSNotification.Name.init(rawValue: appMoneyLoadEndNoticeName), object: nil)
        
        
        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.refreshView()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func receiveMoneyLoadEnd() {
        self.refreshView()
        
    }



    @objc func shopChangeShopClick(){
        let appTabVc  = self.navigationController?.tabBarController as? AppTabBarViewController
        appTabVc?.showChangeShop()
    }
    
    func setupTableView() {
        self.shopWrapperView.qmui_borderWidth = 0.5
        self.shopWrapperView.qmui_borderColor = UIColor.white
        self.shopWrapperView.qmui_borderPosition = [.bottom,.top,.left,.left]
        self.shopWrapperView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(shopChangeShopClick))
        self.shopWrapperView.addGestureRecognizer(tap)
        self.denomiationLabel.text = LanguageHelper.getString(key: "denomtiationLabel")
        self.currencyLabel.text = LanguageHelper.getString(key: "currencyTabLabel")
        self.buyingLabel.text = LanguageHelper.getString(key: "buyingLabel")
        self.sellingLabel.text = LanguageHelper.getString(key: "sellingLabel")
        
        self.tableView.rowHeight = 54
        self.tableView.register(UINib(nibName: "ExchangeViewCell", bundle: nil), forCellReuseIdentifier: "cellItem")
        self.tableHeader.qmui_borderColor = UIColor.qmui_color(withHexString: "#d5d5d5")
        self.tableHeader.qmui_borderWidth = 0.5
        self.tableHeader.qmui_borderPosition  = .bottom
        self.tableView.separatorStyle = .none
        
        self.timeLabel.text = lastUpdateTime
        self.currentShopNameLabel.text = currentShop?.title
        let header = MJRefreshNormalHeader(refreshingBlock: {
            //            self.startRoate()
            NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: changeShopNoticeName), object: nil)
        })
        header?.lastUpdatedTimeLabel.isHidden = true
        header?.stateLabel.isHidden = true
        self.tableView.mj_header = header
       
        
       
      
        
    }
    
    func startRoate() {
       let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        rotationAnimation.toValue = NSNumber.init(value: Double.pi * 2.0)
        rotationAnimation.duration = 1
        rotationAnimation.repeatCount = HUGE
        self.refreshButton.layer.add(rotationAnimation, forKey: "rotationAnimation")
    }
    
    func stopRoate()  {
        self.refreshButton.layer.removeAllAnimations()
    }
    
    
    func refreshView() {
        self.timeLabel.text = lastUpdateTime
        self.currentShopNameLabel.text = currentShop?.title
        self.tableView.reloadData()
        self.tableView.mj_header.endRefreshing()
        stopRoate()
        
    }
    
    func loadRates()  {
//        provider.rx.request(WE.rate()).filterSuccessfulStatusCodes().mapString().subscribe(onSuccess: { (result) in
        
//            if let items =  [RateItem].deserialize(from: result) as? [RateItem] {
//                appRateItems.removeAll()
//                appRateItems.append(contentsOf: items)
//                lastUpdateTime = Date()
//                let dformatter = DateFormatter()
//                dformatter.dateFormat = "YYYY-MM-DD HH:mm:ss"
//                self.timeLabel.text = dformatter.string(from: lastUpdateTime)
//            }
//            self.tableView.mj_header.endRefreshing()
//
//        }) { (_) in
//            self.showEmptyView(withText: "network error", detailText: "", buttonTitle: nil, buttonAction: nil)
//        }
    }
    
    
    
    
    
    
    @IBAction func refreshClick(_ sender: UIButton) {
        self.tableView.mj_header.beginRefreshing()
        
    }
    
    func setupHeaderView() {
        
        let topLogoView =  TopLogoView.loadView()
        topLogoView.titleLabel.text = LanguageHelper.getString(key: "CFBundleDisplayName")
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: topLogoView)
        let telBtn = UIBarButtonItem.qmui_item(with: #imageLiteral(resourceName: "icon_tel"), target: self, action: #selector(telClick))
        let convertBtn = UIBarButtonItem.qmui_item(with: #imageLiteral(resourceName: "icon_covert"), target: self, action: #selector(convertClick))
        
        self.navigationItem.rightBarButtonItems = [telBtn,convertBtn]
        
    }

    @objc func convertClick(){
        let tabVc =  self.navigationController?.tabBarController as? AppTabBarViewController
        tabVc?.showConvert()
    }

    @objc func telClick(){
        let tabVc =  self.navigationController?.tabBarController as? AppTabBarViewController
        tabVc?.telClick()
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
extension ExchangeViewController:QMUITableViewDataSource,QMUITextFieldDelegate,QMUITableViewDelegate,ExchangeViewCellDelegate {
    func onClickShowHide(section: Int) {
        let oldIndex = openSection
        
        if openSection == section {
            openSection = -1
        }else {
            openSection = section
        }
//        var sets:IndexSet
//        if oldIndex == -1 {
//             sets = IndexSet(arrayLiteral: section)
//        }else {
//             sets = IndexSet(arrayLiteral: oldIndex,section)
//        }
//       self.tableView.reloadSections(sets, with: UITableView.RowAnimation.automatic)
        self.tableView.reloadData()
    }
    
    func onCellClick(section: Int, row: Int) {
        if !isLogin {
            Utils.pushLogin()
        }else {
            let item = appMoneyItems[section].rates[row]
            let apVc = SubmitOrderViewController()
            item.money = appMoneyItems[section]
            apVc.rate = item
            
            
            self.navigationController?.pushViewController(apVc, animated: true)
        }
    }
    
  
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if openSection == section {
            let moneyItem = appMoneyItems[section]
            
            return moneyItem.rates.count - 1
        }else {
            return 0
        }
       
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return appMoneyItems.count
    }
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = ExchangeViewCell.loadView()
        view.section = section
        view.row = 0
        view.delegate = self
        let screenWidth = UIScreen.main.bounds.width
        view.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 54)
        
        let money = appMoneyItems[section]
        let item = money.rates[0]
        if  money.rates.count > 1 {
            view.arrowIconView.isHidden = false
           
        }else {
            view.arrowIconView.isHidden = true
        }
        view.icon.kf.setImage(with: URL(string: IMAGE_HOST + money.image))
        view.currency.text = money.ex_title
        view.currency.isHidden = false
        view.icon.isHidden = false
        view.demnomiationLabel.text = item.link
        view.buying.text = "\(item.buying)"
        view.selling.text = "\(item.selling)"
        
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 54
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell =  tableView.dequeueReusableCell(withIdentifier: "cellItem") as! ExchangeViewCell
        
        cell.delegate = self
        cell.section = indexPath.section
        cell.row = indexPath.row + 1
        let item = appMoneyItems[indexPath.section].rates[indexPath.row + 1]
        let money = appMoneyItems[indexPath.section]
        cell.icon.kf.setImage(with: URL(string: IMAGE_HOST + money.image))
        cell.currency.text = money.ex_title
        cell.demnomiationLabel.text = item.link
        cell.currency.isHidden = true
        cell.buying.text = "\(item.buying)"
        cell.selling.text = "\(item.selling)"
       
        
        return cell
    }
    
   
    
    
}
